#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# 文件: logger.py
# 说明:
# 时间: 2021/11/06 23:26:09
# 作者: Azure
# 版本: 1.0

from time import localtime, strftime
from os.path import exists
from os import makedirs
from shutil import move
from .command import LoggerCommand
from .exception import SavedataError
from .email import Email


class Logger(object):
    def __init__(self, emaildata: dict, logpath: str = './log.log', is_email: bool = False) -> None:
        super().__init__()
        self.__logpath = logpath
        self.__is_email = is_email
        self.__logstorefolder = LoggerCommand.LOG_STORE
        self.__emaildata = emaildata
        # 如果log存档不存在则创建文件夹
        if not exists(self.__logstorefolder):
            makedirs(self.__logstorefolder)
        # 如果log.log不存在则创建
        if not exists(logpath):
            open(logpath, 'a+').close()

    # 获取调用时的时间
    def __now(self, is_filename: bool = False):
        '''2021-11-06 H:M:S'''
        if not is_filename:
            return strftime(r'%Y-%m-%d %H:%M:%S', localtime())
        else:
            return strftime(r'%Y%m%d%H', localtime())

    def __savedata(self, con: str, tag: str, is_email: bool = False):
        '''写入文件'''
        try:
            # 先进行计数
            with open(self.__logpath, 'r', encoding='utf-8') as fr:
                logrows_num = len(fr.readlines())
            # 如果行数大于设定值，则进行归档
            if LoggerCommand.MAX_ROWS_NUM != None and logrows_num >= LoggerCommand.MAX_ROWS_NUM:
                # 进行归档
                # 归档时候的名字，用日期命名，重复的改变序号
                num = -1
                while True:
                    num += 1
                    _new_name = f'{self.__logstorefolder}/{self.__now(True)}-{num}.log'
                    if not exists(_new_name):
                        move(self.__logpath, _new_name)
                        break
                # 此时log已经move到了store，需要新建一个
                open(self.__logpath, 'a+', encoding='utf-8').close()
            # 写入日志内容
            _fin_con = f'{self.__now()} {tag} {con}'
            # 打印日志内容
            print(_fin_con)
            fin_con = f'{_fin_con}\n'
            with open(self.__logpath, 'a+', encoding='utf-8') as fr:
                fr.write(fin_con)
            if is_email:
                email = Email(self.__emaildata)
                email.sendtome(_fin_con)
        except Exception as e:
            raise SavedataError(f'保存数据时错误：{e}')

    def info(self, con: str):
        '''写入普通信息'''
        return self.__savedata(con, 'info')

    def warn(self, con: str):
        return self.__savedata(con, 'warn')

    def mail(self, con: str):
        if self.__is_email:
            # mail功能开关
            return self.__savedata(con, 'MAIL', True)
        else:
            return self.__savedata(con, 'NOTICE')
